home *** CD-ROM | disk | FTP | other *** search
/ Amiga Developer CD 2.1 / Amiga Developer CD v2.1.iso / Reference / Amiga_Mail_Vol2 / Archives / Plain / jf92 / NetApps / NetApps.txt < prev   
Encoding:
Text File  |  1992-01-03  |  38.1 KB  |  751 lines

  1. (c)  Copyright 1992 Commodore-Amiga, Inc.   All rights reserved.
  2. The information contained herein is subject to change without notice,
  3. and is provided "as is" without warranty of any kind, either expressed
  4. or implied.  The entire risk as to the use of this information is
  5. assumed by the user.
  6.  
  7.  
  8. Developing Network Applications for the Amiga
  9.  
  10. by Dale Larson
  11.  
  12.  
  13.  
  14. When you run a wire between two or more computers, you have a network.  Big
  15. Deal.  When your applications use that wire however, you have a revolution.
  16. Although some of the following software is only internal or experimental, these
  17. are things I can do now with my Amiga, with software that I have now:
  18.  
  19. o  From my Amiga, I can transparently access filesystems on Suns, on the local
  20. Vax system (cbmvax), and on other Amigas.
  21.  
  22. o  Whenever I print, I send my files to a network printer.
  23.  
  24. o  I continuously receive mail on my Amiga--from as far as Seattle, Sydney and
  25. Denmark, and near as a desk next to mine.
  26.  
  27. o  Every night when I go home, my Amigas at work (and several others) are used
  28. to do distributed graphics rendering.  The process is started over the network
  29. and all data is sent over the network.  A picture that would have taken a week
  30. can be finished overnight.
  31.  
  32. In the scheme of what is possible, this is only the tip of the iceberg.
  33.  
  34. o  In a high school environment, a network could allow students to
  35. interactively participate in computer simulations.  It could allow them to
  36. collaborate electronically.  It could allow teachers to electronically monitor
  37. and assist students.  It could save schools money because peripherals such as
  38. printers, hard-drives and CD-ROMs could be easily shared.  Even the
  39. computational power of one expensive machine could be shared by the students.
  40.  
  41. o  A small office can use a network for an email-like facility for phone
  42. messages and other notes.  Another application might replace the intercom.
  43. Form letters can be kept in a central database accessed by a word processor.  A
  44. distributed appointment calendar could allow a secretary to add a new
  45. appointment even as the boss is looking at what his afternoon schedule is.  A
  46. distributed database application would allow access to such things as a central
  47. client database, outstanding orders and the present inventory.
  48.  
  49. o Imagine multi-player games that use the computational power of each machine
  50. connected by a high speed Local Area Network (LAN).
  51.  
  52. o  In a software development environment, several programmers can work on the
  53. same project, updating the same sources.  Debugging information could be sent
  54. over the network, or a debugger on one machine could control the programs on
  55. others (For example, there is a version of Wack that runs over a network).
  56.  
  57. o  Multimedia applications might do any number of exciting things with the
  58. network.  A few of the applications which have been experimented with on other
  59. machines are: real-time audio and video conferencing, interactive demos for
  60. groups, and shared electronic blackboards.
  61.  
  62. In much the same way as all applications are candidates for a GUI interface,
  63. all applications are candidates for becoming network applications.  The GUI has
  64. only changed the ways in which people interact with their computers.  Networks
  65. will change the ways in which people interact with each other.
  66.  
  67. This article introduces some of the principles of writing network programs
  68. using the AS225's Berkeley Socket interface.  Even more so than in most of
  69. software development, networking seems simple in theory, but, in reality, gets
  70. complicated in a hurry.  To develop network software for AS225, you will need
  71. to obtain the Network Developer's kit from CATS.  It has all the necessary
  72. include files and Autodocs to develop for the AS225's socket.library.  Also,
  73. you should plan read at least some of the material in the ``References''
  74. section of this article.
  75.  
  76.  
  77. Protocol Layers and the Berkeley Sockets Interface
  78.  
  79. Network applications should always be written to the Application Programmer's
  80. Interface (API) of a particular protocol, not to the network hardware.  Network
  81. standards usually include several protocols layered one on top of another.
  82. These groups are often referred to as protocol stacks.  At the lowest level,
  83. one of the protocols must interface to some network hardware.  Each layer adds
  84. some abstraction to using the network on a lower level.  This serves to make it
  85. easier to program network software as the developer doesn't have to deal with
  86. networking details that are well below the level of the software under
  87. development.
  88.  
  89. The International Standards Organization (ISO) has created a reference model on
  90. which to base new network layerings.  The ISO 7-Layer Reference Model of Open
  91. Systems Interconnection looks like this:
  92.  
  93.  
  94.                  ------------------------------------
  95.                 | 7  Application                     |
  96.                 |------------------------------------|
  97.                 | 6  Presentation                    |
  98.                 |------------------------------------|
  99.                 | 5  Session                         |
  100.                 |------------------------------------|
  101.                 | 4  Transport                       |
  102.                 |------------------------------------|
  103.                 | 3  Network                         |
  104.                 |------------------------------------|
  105.                 | 2  Data Link (Hardware Interface)  |
  106.                 |------------------------------------|
  107.                 | 1  Physical Hardware Connection    |
  108.                  ------------------------------------
  109.  
  110.                      ISO-7 Layer Reference Model
  111.  
  112.  
  113.  
  114. The only protocol stack for the Amiga which is currently available from
  115. Commodore is TCP/IP.  Our AS225 software package includes the standard TCP/IP
  116. protocols and several standard Internet applications.  It has the same API as
  117. most Unix machines running TCP/IP using the Berkeley Sockets interface.
  118.  
  119. Unix was designed to have a common method of accessing both files and devices.
  120. Before a Unix application can perform any I/O operations on a file, it has to
  121. open() it.  The Unix open call returns an integer called a file descriptor that
  122. corresponds to the open file.  The application uses this file descriptor to
  123. manipulate the file.
  124.  
  125. This method of I/O is not quite general enough for networking.  Instead, there
  126. is the Berkeley Sockets interface.  A socket is an entity used to send and
  127. receive data across a network.  A socket can be ``plugged in'' or bound
  128. directly to the socket of some other application on another machine somewhere
  129. on the network.  Like the Unix file system, applications access their sockets
  130. using a file descriptor, although it is typically referred to as a socket
  131. descriptor.
  132.  
  133. Thousands of network applications have been written to the socket interface.
  134. AS225 has been shipping since December, 1990, and everything needed to write
  135. network applications for AS225 is included on the 1991 DevCon disks and on the
  136. Network Developer's Disk.
  137.  
  138. On the Amiga, layers 1 and 2 should always be the network hardware and SANA-II
  139. Network Device Driver (SANA-II defines the lowest level software interface to
  140. networking hardware).  In AS225, layer 3 is the IP and ICMP protocols of the
  141. TCP/IP protocol stack.  These protocols aren't used directly by application
  142. developers.  Essentially, they handle machine to machine communication.  The
  143. transport layer uses the network layer (and the layers below it) to provide
  144. communication between individual processes on different machines.  Most current
  145. network applications use transport protocols.  The transport protocols in
  146. TCP/IP are TCP and UDP.
  147.  
  148. The TCP transport protocol is a connection-oriented, stream protocol.
  149. Basically, the socket of one application connects to the socket of another
  150. application and they communicate across the network in data streams.  The two
  151. applications can be running on arbitrary machines on a network.  The big plus
  152. of using TCP is that it is a reliable protocol.  If the data is put in one end
  153. of a TCP stream, it either gets to the other end intact, or not at all (which
  154. causes an error at the sender's end).  This makes it easier to program
  155. applications because the application programmer does not have to worry about
  156. packet corruption.
  157.  
  158. UDP is a connectionless, datagram protocol.  An application using UDP sends
  159. datagrams to some other application on the network.  A datagram is a
  160. fixed-length message.  Because the sockets of UDP applications are not
  161. connected, a datagram sent from a socket can be sent to an arbitrary UDP
  162. socket.  Unlike TCP, UDP is not a reliable protocol, so an application that
  163. uses UDP has to account for errors that can occur during transmission.
  164.  
  165. The details of all the various protocols and how they behave are quite complex
  166. and are beyond the scope of this article.  This article deals with the
  167. difference between connection-oriented stream protocols (sockets which are
  168. obtained as type SOCK_STREAM) and connectionless datagram protocols (type
  169. SOCK_DGRAM).
  170.  
  171. The Amiga Shared Socket Library (socket.library) is Commodore's implementation
  172. of the standard functions for manipulating, sending data to, and receiving data
  173. from sockets.  Other network APIs for TCP/IP have been written for other
  174. platforms (most notably TLI on Unix SVR4 systems).  Programs written using
  175. sockets on one machine can communicate just fine with programs written using
  176. another API (i.e., TLI) on another machine.  Sockets are not specific to
  177. TCP/IP.  They can be used with different ``domains''.  TCP/IP is one domain,
  178. another network protocol is another domain and local Inter-Process
  179. Communication (IPC) is yet another.  Our socket library currently supports only
  180. TCP/IP.
  181.  
  182. Layers 5 and 6 of the OSI model, the presentation and session layers, do not
  183. exist in TCP/IP, or most other protocol stacks.  So with TCP/IP on the Amiga,
  184. the protocol stack looks like this:
  185.  
  186.                  -------------------------------------------
  187.                 | Application                               |
  188.                 |-------------------------------------------|
  189.                 | Transport (TCP, UDP)                      |
  190.                 |-------------------------------------------|
  191.                 | Network   (IP, ICMP)                      |
  192.                 |-------------------------------------------|
  193.                 | Data Link (SANA-II Network Device Driver) |
  194.                 |-------------------------------------------|
  195.                 | Hardware  (ethernet, arcnet, ...)         |
  196.                  -------------------------------------------
  197.  
  198.                            TCP/IP Protocol Stack
  199.  
  200.  
  201.  
  202. In spite of the fact that protocols come in a stack, your application will only
  203. come into direct contact with a protocol at the top of the stack.  In the case
  204. of TCP/IP, this is the transport layer.  In theory, you are not required to
  205. know protocols below the one used for your application.  In practice,
  206. higher-level protocols are often described in terms of additions to lower-level
  207. protocols.
  208.  
  209.  
  210. Network Applications
  211.  
  212. Most network applications are built around a client/server model.  In the
  213. client/server model, a server application runs on one machine somewhere on a
  214. network.  That server waits for a request for a particular service it provides.
  215. These requests come from client applications that are running on other machines
  216. on the network.  A service can be as simple as echoing back text sent to the
  217. server or as complex as providing a remote login facility.  For example, the
  218. ftp (File Transfer Program) application copies files between networked
  219. machines.  Ftp actually consists of two programs, a client and a server.  The
  220. server waits around for a client to request some service, like listing a
  221. directory or transferring a file.
  222.  
  223. On most networks, each machine is capable of running both client and server
  224. programs simultaneously, but on some networks a machine is either a client or a
  225. server and may only run programs of that type.  The focus of this article is
  226. peer-to-peer networks (the former), not client-server networks (the latter).
  227.  
  228.  
  229. Application Protocols
  230.  
  231. Every networked program must agree on how to send data across the network and
  232. on what meaning to attach to that data.  Therefore, the application itself has
  233. a protocol.  This is the application layer of the ISO reference model and
  234. TCP/IP protocol stack.  The application-specific protocol can include such
  235. things as what transport protocol will be used, what initialization takes
  236. place, how any security is implemented, what format data will be in, etc.
  237.  
  238. For standard Internet applications (ftp for example), the application protocols
  239. are specified in detail in one or more reference documents called Requests for
  240. Comments, or RFCs.  RFCs are the specifications for Internet protocols and
  241. standard applications.  Even if you aren't implementing a standard Internet
  242. application, the RFCs offer insight into the complexities of application
  243. protocols and how they should be specified.  See the ``References'' section of
  244. this article for more information on RFCs and standard Internet applications.
  245.  
  246. Normally application protocols are general enough that network applications can
  247. be ported to any machine which supports the network protocol.  Neither the
  248. client nor the server knows (or cares) what type of machine is at the other
  249. end.  Sometimes only one half of the application (client or server) is
  250. available for a given machine.  For example, the currently released version of
  251. AS225 includes an NFS (Network File System) client program, but no NFS server
  252. program.  To use NFS with AS225 requires access to any machine with an NFS
  253. server--it does not require any particular type of machine.
  254.  
  255.  
  256. Kinds of Servers
  257.  
  258. There are two kinds of servers.  Those which process one request at a time are
  259. called ``iterative servers''.  Those which simultaneously service multiple
  260. requests (often by spawning a process to handle each request) are called
  261. ``concurrent servers''.  Iterative servers are generally easier to write, but
  262. are only suitable for services which can be handled quickly and/or will not be
  263. accessed by multiple clients.  Applications which use connectionless protocols
  264. (UDP) frequently have iterative servers, while applications with
  265. connection-oriented protocols (TCP) usually have concurrent servers.
  266.  
  267.  
  268. Addresses
  269.  
  270. All data on the network is sent to and from network addresses.  There are many
  271. different types of network addresses, at least one type for each layer of the
  272. protocol stack.  For example, the Network layer of the TCP/IP protocol stack
  273. uses the IP and ICMP protocols which use 32-bit internet addresses (which are
  274. usually represented in ``dotted decimal notation'' e.g., 192.9.210.4) to talk
  275. to a specific machine at a specific internet-style address.  When applications
  276. communicate with each other, they usually use a transport layer protocol,
  277. therefore the data is sent from one transport address to another.  A transport
  278. address generally corresponds to a specific program running on a specific
  279. machine somewhere on a network.
  280.  
  281. A transport address consists of three parts: a protocol, a host address, and a
  282. process association.  In AS225, the protocol in a transport address is either
  283. TCP or UDP.  The host address is dependent upon the protocol, but in AS225, the
  284. host address is always the internet address of the host.  The process
  285. association is also protocol dependent, and in AS225, the process association
  286. is a port number.  TCP/IP port numbers are 16-bit integers that are used by the
  287. transport protocols on each host to direct network traffic to a specific
  288. process running on the machine at that internet address.
  289.  
  290. The set of port numbers is unique to each protocol.  For example, port number
  291. 42 for UDP might belong to a different process than that which belongs to port
  292. number 42 for TCP.  Without port numbers, multiple network programs could not
  293. run simultaneously.
  294.  
  295. Transport protocols are analogous in some ways to Amiga Exec devices.  In such
  296. an analogy, there is a TCP device and a UDP device.  Each device has about
  297. 65,000 units and none of the units can be opened in shared mode.
  298.  
  299. Once a socket is created, it has to be bound to a transport address.  An
  300. application binds an address to a socket in one of two ways.  The binding can
  301. be made explicitly by the program to a specific transport address (using the
  302. bind() call).  Servers normally use this type of binding.  In this case, the
  303. server uses a preset, ``well-known'' port number in its transport address.  The
  304. port number is well-known because all of the server's possible clients know
  305. what that particular server's port number is.   Because these clients know the
  306. server's port number, the clients can construct a transport address for that
  307. particular service on any machine that runs that server.  For example, the
  308. default, well-known port number for ftp is 21.  If a client wants to use ftp to
  309. transfer files from a machine at the internet address 192.9.210.4, it can use
  310. ftp's port number, the machine's internet address, and the protocol (ftp uses
  311. TCP) to find the ftp server at 192.9.210.4.  As long as there is an ftp server
  312. running at 192.9.210.4, the client should have no problem finding the server.
  313. This type of socket is analogous to a public message port.
  314.  
  315. The other way to bind a socket to a transport address is to let the socket
  316. library arbitrarily choose a port number for the application.  Normally client
  317. applications bind this way because a client does not need a well-known address.
  318. The client supplies the server with its transport address when it sets up
  319. communication with the server.  This type of socket is analogous to a private
  320. Exec message port.
  321.  
  322.  
  323.  
  324. Finding Servers
  325.  
  326. A client ``finds'' its server by the server's transport address.  As was
  327. mentioned eariler, the transport address consists of a protocol, a host
  328. address, and a port number.  For the TCP/IP protocol stack, the protocol is
  329. either TCP or UDP.
  330.  
  331. The next thing the client needs to build after the transport address is an
  332. internet address for the server's machine.  Normally the client obtains that
  333. address from the user.  The address can be in one of two forms, an internet
  334. address (in dotted decimal notation), or a host name which is an ASCII string
  335. that corresponds to the host's internet address.  If the client gets a host
  336. name, it asks the socket.library what internet address corresponds to the host
  337. name.
  338.  
  339. When a server starts, it opens a socket and bind()s that socket using the
  340. server's well-known port number.  There are two ways for the server's
  341. well-known port to become well-known:
  342.  
  343.   1) A server's well-known port number can be hard-coded into both the
  344.      client and server.  This is recommended for prototyping new programs, but
  345.      is a Very Bad Thing for programs which will be distributed.  The port
  346.      number is arbitrary, but must not be one of the reserved ports (see the
  347.      next section) and must not conflict with a port number already in use.
  348.  
  349.   2) Port numbers can be configurable.  All distributed network
  350.      applications should use configurable port numbers.  In programs written
  351.      for AS225, you should use the inet:db/services file to configure a port
  352.      number.  The function getservbyname() accepts a protocol (UDP or TCP) and
  353.      the name of a well-known server and returns the port number of that
  354.      service.  This requires you to configure your application by adding an
  355.      entry to the inet:db/services file on every machine which will use the
  356.      application.  Many standard Internet applications and Unix remote services
  357.      are already in the inet:db/services file that comes with AS225.  If your
  358.      application isn't already included, your installation scripts should add
  359.      the entry for your application to inet:db/services.  Offer a default
  360.      value, but let your user actually pick the number since your port number
  361.      must not conflict with another (pre-existing) port number.
  362.  
  363.  
  364. Reserved Ports
  365.  
  366. Port numbers 1-255 are reserved for standard Internet applications (like ftp)
  367. and port numbers 256-1023 are reserved for standard Unix remote services (which
  368. are often available for machines other than Unix).  You should never choose any
  369. of these port numbers for your application unless it is an implementation of a
  370. standard for which the port number is reserved.  For more information on port
  371. numbering and reserved ports, see the ``References'' section at the end of this
  372. article.
  373.  
  374.  
  375.  
  376. Skeleton for Applications Using TCP (connection-based)
  377.  
  378. Aside from the special quirks of the socket.library (which is discussed in the
  379. ``Shared Socket Library'' section below), the basic outline of the core of most
  380. client/server model applications written with TCP starts with the server:
  381.  
  382. Create a socket:
  383.  
  384. int socket(int family, int type, int protocol)
  385.  
  386. Where family specifies the protocol family (which for the TCP/IP protocol stack
  387. is AF_INET from <sys/socket.h>), type specifies the abstract type of
  388. communication (either SOCK_STREAM for TCP or SOCK_DGRAM for UDP), and protocol
  389. is not generally used in the TCP/IP protocol stack and should be set to zero.
  390. If socket() fails, it returns a -1, otherwise it returns a socket descriptor.
  391.  
  392. Next, get the well-known port number of the server's service:
  393.  
  394. struct servent *getservbyname(char *family, char *service)
  395.  
  396. where family is one of two strings, "tcp" or "udp".  The service argument is
  397. the name of the service that this server provides.  The function returns a NULL
  398. if there was an error.  Otherwise, it returns pointer to a servent structure
  399. (from <netdb.h>):
  400.  
  401. struct  servent {
  402.     char   *s_name;      /* official service name */
  403.     char   **s_aliases;     /* alias list */
  404.     int    s_port;       /* port # */
  405.     char   *s_proto;     /* protocol to use */
  406. };
  407.  
  408.  
  409. Next, build a sockaddr_in (from <netinet/in.h>) structure using the port number
  410. from the s_port field of the servent structure returned by getservbyname():
  411.  
  412. struct in_addr {
  413.     u_long s_addr;
  414. };
  415.  
  416. struct sockaddr_in {
  417.     short     sin_family;        /* address family.  Make this AF_INET for TCP/IP */
  418.     u_short   sin_port;          /* the port number (the value from servent.s_port) */
  419.     struct    in_addr sin_addr;  /* internet address.  For TCP/IP, make sin_addr.s_addr
  420.                                     INADDR_ANY.  Bind will know what to do with this. */
  421.     char      sin_zero[8];       /* unused by TCP/IP */
  422. };
  423.  
  424.  
  425. The sockaddr_in structure is a TCP/IP specific version of the sockaddr
  426. structure.
  427.  
  428. Now give the sockaddr_in to bind() in order to attach a specific address to the
  429. socket:
  430.  
  431. int bind(int servsocket, struct sockaddr *name, int namelength)
  432.  
  433. where, servsocket is the socket descriptor of the socket that needs a specific
  434. address, name is a pointer to the sockaddr structure (or, for TCP/IP purposes,
  435. a sockaddr_in structure) that describes the address, and namelength is the
  436. length of the sockaddr structure.
  437.  
  438. Once the socket is bound to an address, the server calls listen() to indicate
  439. that it is waiting to receive connections.
  440.  
  441. The server is ready to start its main processing loop.  The accept() function
  442. waits for and accepts a new connection at a socket:
  443.  
  444. int accept(int servsocket, struct sockaddr *name, int namelength)
  445.  
  446. where, servsocket is the socket (descriptor) on which the server is waiting for
  447. connections, name points to a buffer where accept() copies a sockaddr structure
  448. describing the client that is trying to connect to the server, and namelength
  449. is the length of the name buffer.
  450.  
  451. If accept() fails, it returns a negative value, otherwise accept() returns a
  452. socket descriptor of a new socket that is connected to the client's socket.
  453.  
  454. The server can communicate with the client using the new socket while it
  455. continues to listen to its original socket for new connections.  The server may
  456. serve one client at a time (an iterative server), or give the new socket (the
  457. one returned by accept()) to a new process so it can handle talking to the
  458. client (a concurrent server).
  459.  
  460. Setting up the client is similar to setting up the server.  You have to create
  461. a socket, find the service's well-known port number, and initialize a
  462. sockaddr_in structure that refers to the server.  Creating the socket and
  463. finding the service's port number are identical to the method described above.
  464.  
  465. To initialize the sockaddr_in structure, fill in the sin_family (AF_INET) and
  466. sin_port (service's well-known port number) fields as in the server.  To fill
  467. in the sin_addr field, the client needs to find the internet address of the
  468. server's machine.  The client has to find this from either from an ASCII string
  469. of the IP address or the host name (either of which the client will probably
  470. get from the user).  The inet_addr() function accepts an ASCII string of a
  471. numeric IP address and returns the internet address to put in the sockaddr_in's
  472. sin_addr.s_addr field.  If the client only has the host name, it has to call
  473. gethostbyname() to find out the server's machine address:
  474.  
  475. struct hostent *gethostbyname(char *hostname)
  476.  
  477. The parameter hostname is an ASCII string naming the host.  This function
  478. figures out the address of the host (usually by looking it up in the
  479. inet:db/hosts file).  This function returns a pointer to a hostent structure:
  480.  
  481. struct  hostent {
  482.     char   *h_name;       /* official name of host */
  483.     char   **h_aliases;   /* alias list */
  484.     int    h_addrtype;    /* host address type */
  485.     int    h_length;      /* length of address */
  486.     char   **h_addr_list; /* list of addresses from name server */
  487. #define  h_addr  h_addr_list[0]  /* address, for backward compatibility */
  488. };
  489.  
  490.  
  491. The #defined field, h_addr, contains a pointer to an in_addr structure, which
  492. contains the actual host address.  Copy this value into the
  493. sockaddr_in.sin_addr.s_addr field.
  494.  
  495. Now the client needs to establish a connection between itself and the server.
  496. It does this with the connect() function():
  497.  
  498. int connect(int clientsocket, struct sockaddr *servname, int namelength)
  499.  
  500. where, clientsocket is the socket the client created earlier, servname points
  501. to the sockaddr_in structure the client just built, and namelength is the
  502. length of that sockaddr_in structure.
  503.  
  504. The server and client communicate using the send() and recv() functions:
  505.  
  506. int send(int socket, char *buf, int buflength, int flags)
  507. int recv(int socket, char *buf, int buflength, int flags)
  508.  
  509. where, socket is the socket to send to/receive from, buf is a buffer that
  510. contains the data to transmit/is a place for recv() to put the data it
  511. receives, buflength is the length of buf, and flags is beyond the scope of this
  512. article.  For the moment, you can set it to zero.
  513.  
  514. The data is a continuous stream, with any meaning assigned by the application
  515. protocol (not to be confused with the network protocol).  The data is always
  516. received either intact or not at all.  The data almost always gets there unless
  517. there is a serious network or host machine problem.  When the communications
  518. are finished, both sides s_close() the sockets which were connected.
  519.  
  520.  
  521. Skeleton for Applications Using UDP (connectionless)
  522.  
  523. The basic outline of most client/server model applications written with UDP
  524. look something like this:
  525.  
  526. Server gets a socket with socket(), gets a port number with getservbyname(),
  527. builds a sockaddr_in structure describing the server, and gives that structure
  528. to bind() in order to attach a specific address to the socket.  It then loops,
  529. waiting to recvfrom() any incoming datagrams and responding to any requests in
  530. those datagrams.
  531.  
  532. int recvfrom(int socket, char *buf, int buflength, int flags, struct sockaddr
  533. *clientname, int namelength)
  534.  
  535. The recvfrom() function is similar to the recv() function except it has two
  536. extra parameters.  clientname is a buffer for a sockaddr_in structure.  When
  537. recvfrom() receives a datagram from some application on the network, it fills
  538. in clientname with the transport address of that application.  The size of the
  539. structure is namelength.
  540.  
  541. The client gets a server hostname from the user, gets a socket(), gets the
  542. server's port number with getservbyname(), builds a sockaddr_in structure
  543. describing the server, and sendto()s a datagram to the server's well-known
  544. address:
  545.  
  546. int sendto(int socket, char *buf, int buflength, int flags, struct sockaddr
  547. *servername, int namelength) The client either waits for the server to send
  548. back a datagram to the client's socket, or give up because the server took too
  549. much time to reply.  The client does this by calling select().  This function
  550. puts the client to sleep until either a particular set of sockets is ready for
  551. reading, writing, or exception processing, or after a timeout period has passed
  552. without any activity.
  553.  
  554. int select(int numsocks, fd_set *readsocks, fd_set *writesocks,
  555.            fd_set *exceptsocks, struct timeval *timeout)
  556.  
  557. The numsocks parameter is 1 plus the number of sockets select() is waiting on.
  558. The readsocks, writesocks, and exceptsocks parameters are each a bitmask which
  559. tells select() which socket (or sockets) to wait for activity on.  The fd_set
  560. structure (defined in <sys/types.h>), is basically a handle to one of these
  561. bitmasks.  Programs cannot directly manipulate the bits in these masks.
  562. Instead, there are functions to do this:
  563.  
  564. FD_ZERO(struct fd_set *mymask)                /* clear all bits in mymask */
  565. FD_SET(int mysocket, struct fd_set *mymask)   /* turn on the bit for mysocket
  566.                                                  in mymask */
  567. FD_CLR(int mysocket, struct fd_set *mymask)   /* turn off the bit for mysocket
  568.                                                  in mymask */
  569. FD_ISSET(int mysocket, struct fd_set *mymask) /* test if mysocket's bit
  570.                                                  in mymask is set */
  571.  
  572. For the purposes of this article, the only relevant mask is readsocks, because
  573. the client is only waiting to read from a socket.  Since the client isn't
  574. interested in the other masks, it makes writesocks and exceptsocks NULL.
  575.  
  576. The last parameter, timeout, sets the maximum amount of time that select()
  577. should wait for activity on the sockets it is watching.
  578.  
  579. When select() returns, its return value is either -1 if it failed, 0 if there
  580. was a timeout, or a positive number, which is the number of sockets that became
  581. ready.  When select returns, it sets the bits in the bitmasks according to
  582. which socket (or sockets) became ready.
  583.  
  584. When select() returns, if a socket became ready, the client calls recvfrom() to
  585. get the datagram the server sent back.  On timeout, the client might try to
  586. re-send the datagram since it may have been lost or corrupted.  Datagrams can
  587. be also be received in an order different from that in which they were sent and
  588. can be received in duplicate.
  589.  
  590.  
  591. Which Protocol Is Right For My Application?
  592.  
  593. Generally, if your application requires moving bulk data to far away places,
  594. you should be using TCP.  For many other applications, TCP is also appropriate
  595. just because its reliability makes it easy to use.  TCP is so easy to use
  596. because it provides so much functionality.  The price paid for ease of use is
  597. performance.
  598.  
  599. TCP does a good job of moving bulk data from one side of the planet to another.
  600. For data which will only be sent across one physical network (one LAN), or for
  601. data sent in small pieces, TCP doesn't perform so well.  A much more specific
  602. set of functionality can always provide better performance than the most
  603. general set can. For performance-critical applications which don't move bulk
  604. data, UDP is usually the protocol of choice.  Unfortunately, since UDP doesn't
  605. provide reliability, the application protocol must.  This means a much more
  606. complicated application protocol.  It isn't nearly as bad as it sounds, though,
  607. and Stevens (1990) offers two examples.
  608.  
  609.  
  610. The Shared Socket Library
  611.  
  612. The primary goal of the Shared Socket Library is to provide a network API which
  613. is as compatible with standard Unix as possible.  This makes porting many
  614. applications much easier, but it also creates many little quirks that cannot be
  615. ``fixed''.  The justification behind this is: faithfully emulating Unix's
  616. quirks is better than creating new ones, since at least you can then write more
  617. portable software and only need to remember one set of quirks.  Remember this
  618. when you wish that some function returned *void rather than *foo, etc.  Expect
  619. to get a few spurious compiler warnings from your nice ANSI 'C' compiler.
  620.  
  621. Many functions in socket.library are only needed by those developers porting
  622. standard Unix remote services and probably should not be used by most Amiga
  623. applications.  For example, all the functions dealing with user and group IDs
  624. belong in this category.
  625.  
  626. To use the socket.library functions, the first thing you have to do, of course,
  627. is open it.  This library is a little unconventional because it returns a
  628. different library base for each OpenLibrary() call.  The Shared Socket Library
  629. uses different library bases to keep track of some global data for each process
  630. that opens it.  If you start a new process with a new context, the new process
  631. must open and initialize socket.library.  Tasks should not access the
  632. socket.library, only processes should.
  633.  
  634. Before using any other function in the socket.library, you must call its
  635. function setup_sockets() to initialize the library:
  636.  
  637. ULONG retval = setup_sockets( UWORD max_sockets, int *errnop );
  638.  
  639. where max_sockets is the maximum number of sockets that can be open at once and
  640. errnop points to errno, a global integer that provides details about error
  641. conditions.  This global value is used extensively by the standard socket
  642. functions.  The standard Amiga C startup code (c.o) creates a global variable
  643. labelled ``errno'' which you can use as the global pointer.
  644.  
  645. The setup_sockets() call must be matched with the cleanup_sockets() call.  This
  646. takes care of deallocating system resources that setup_sockets() allocates.
  647.  
  648. The socket.library assumes that all ints are 32-bit values.  If you are using a
  649. compiler which doesn't use 32-bit ints, you must make sure that all ints are
  650. converted to longs by your code.
  651.  
  652. There are a couple of important differences between the AS225 socket.library
  653. and the standard Unix implementation.  When writing softwarefor AS225, you
  654. cannot use the read(), write(), close(), and ioctl() functions on sockets.
  655. These functions come from Unix and apply both to files and sockets.  To avoid
  656. confusion, socket.library does not contain these functions.  Use the
  657. socket.library functions recv(), send(), s_close(), and s_ioctl() instead.
  658.  
  659. The standard Unix implementation has a series of get*() functions.  These
  660. functions return a pointer to a static buffer.  The buffer returned by a call
  661. to getX*() is cleared on the next invocation of getX*().  For example, the
  662. buffer pointed to by the return of gethostent() is cleared by another call to
  663. gethostent(), gethostbyaddr() or gethostbyname(), but not by a call to
  664. getprotoent(), etc.  None of the get*ent(), set*ent() or end*ent() functions
  665. should normally be used except for porting existing programs.
  666.  
  667. The Shared Socket Library contains a function called selectwait().  This
  668. function combines the select() function with the exec.library Wait() function
  669. so that an Amiga networked application can wait on both Amiga events and
  670. network events at the same time.
  671.  
  672. This article, the examples from the Network Developer's disk,  and the include
  673. files and the Autodocs should be enough to get you started.  Writing network
  674. applications can be very complex and difficult, but is well worth the effort.
  675. This article only introduces you to writing network applications for the Amiga
  676. with AS225, and has left a lot unsaid about the socket interface and about
  677. networking in general.  In addition to the Shared Socket Library include files
  678. and Autodocs, the following books and articles are all highly recommended.
  679. Several should be required reading for anyone seriously developing any Amiga
  680. and/or Unix network applications with TCP/IP:
  681.  
  682.  
  683. References
  684.  
  685. Comer, D.E. (1991a), Internetworking with TCP/IP, Volume I, 2d: Principles,
  686. Protocols, and Architecture. Prentice-Hall, ISBN 0-13-468505-9
  687.  
  688.   If you want more detail on how the protocols work (especially how they support
  689.   internetworking), this is the place to look.  Little programming information is
  690.   in this volume.
  691.  
  692. Comer, D.E. and Stevens, D.L. (1991b), Internetworking with TCP/IP, Volume II:
  693. Design, Implementation and Internals. Prentice-Hall, ISBN 0-13-472242-6.
  694.  
  695.   There is more detail here than most application developers will want or need,
  696.   but some subjects (i.e., Out-Of-Band data) are covered here better than in any
  697.   other text.  The text includes a complete TCP/IP implementation for Xinu.  It
  698.   should be easily understandable by Amiga developers, in part, because Xinu
  699.   happens to have a rather Exec-like IPC mechanism.
  700.  
  701. Stevens, W.R. (1990), Unix Network Programming.  Prentice-Hall, ISBN
  702. 0-13-949876-1.
  703.  
  704.   This book starts at the beginning and methodically leads the reader through
  705.   many advanced topics.  If it weren't for the fact that it serves as a reference
  706.   and a tutorial, it could be thought of as the RKMs for AS225 software
  707.   development.  It introduces network protocols in some detail, and sockets in
  708.   great detail.  It includes source and discussion of several real-world
  709.   examples: ping, tftp, rlogin, lpr, rcmd, rmt, etc.  Everyone in the Amiga
  710.   Networking group owns a copy.
  711.  
  712. RFCs
  713.  
  714. All Internet standards start life as Requests For Comments.  They are still
  715. called RFCs even if they become required, recommended, or elective.  If you
  716. wish to implement a standard Internet application, you should obtain any
  717. currently applicable RFC(s) and study them closely.  Here is one way to obtain
  718. RFCs:
  719.  
  720. CSNET:
  721.  
  722. CSNET Coordination and Information Center (CIC)
  723.         Hotline: (617) 873-2777
  724. 10 Moulton Street, Cambridge, MA 02138
  725.         Email:  cic@sh.cs.net
  726.           Info-Server requests to: info-server@sh.cs.net
  727.  
  728. The CSNET Info-Server stocks all RFCs with numbers higher than 900, unless
  729. (like RFC 900) they have been obsoleted by later RFCs.  The Info-Server also
  730. stocks selected RFCs with numbers lower than 900.
  731.  
  732. The CSNET Info-Server is an automatic program that delivers information by
  733. electronic mail.  To order a document from the Info-Server, send a message to
  734. ``info-server@sh.cs.net''.  You do not need a subject field.  The text of your
  735. message must be in a special format, such as:
  736.  
  737.              REQUEST: rfc
  738.               TOPIC: heLP
  739.               Topic: RFC822
  740.              request: END
  741.  
  742. The text may any combination of upper-case and lower-case letters.
  743.  
  744. The above request asks for two documents ``HELP'' and ``RFC822'' from the
  745. collection ``RFC''.  Your message must have a ``REQUEST'' line, and one or more
  746. ``TOPIC:'' lines to specify one or more documents. The optional statement
  747. ``REQUEST: END'' terminates your specification.  Any subsequent text in the
  748. message is ignored by the Info-Server.
  749.  
  750. NOTICE: The Topic: field must be of the form ``rfc822'', and NOT ``822'' or
  751. ``rfc822.txt''.